package org.yuanqiframework.yuanqi.boot.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.web.bind.annotation.*;
import org.yuanqiframework.yuanqi.web.controller.BaseController;
import org.yuanqiframework.yuanqi.web.entity.AjaxResult;
import org.yuanqiframework.yuanqi.boot.sys.dto.SysWebsiteDTO;
import org.yuanqiframework.yuanqi.boot.sys.entity.SysWebsite;
import org.yuanqiframework.yuanqi.boot.sys.service.SysWebsiteService;
import org.yuanqiframework.yuanqi.boot.sys.utils.SysRsaUtils;
import org.yuanqiframework.yuanqi.boot.sys.vo.server.Server;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RequestMapping("/api/sys")
@RestController
public class SystemController extends BaseController {
    @Resource
    private SysWebsiteService sysWebsiteService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping(value = "webInfo")
    public AjaxResult<?> webInfo() {
        return AjaxResult.success(sysWebsiteService.list(new LambdaQueryWrapper<SysWebsite>()
                .orderByAsc(SysWebsite::getId)));
    }

    @GetMapping(value = "website/query")
    public AjaxResult<?> websiteQuery() {
        return AjaxResult.success(sysWebsiteService.list(new LambdaQueryWrapper<SysWebsite>()
                .orderByAsc(SysWebsite::getId)));
    }


    @PostMapping(value = "website/sync")
    public AjaxResult<?> websiteSync(@Valid @RequestBody SysWebsiteDTO sysWebsiteDTO) {
        String keyName = sysWebsiteDTO.getKeyName();
        String settingValue = sysWebsiteDTO.getSettingValue();
        return toAjax(sysWebsiteService.update(new LambdaUpdateWrapper<SysWebsite>()
                .set(SysWebsite::getSettingValue, settingValue)
                .eq(SysWebsite::getKeyName, keyName)
        ));
    }


    @PostMapping(value = "website/syncBatch")
    public AjaxResult<?> websiteSyncBatch(@Valid @RequestBody List<SysWebsiteDTO> sysWebsiteDTOList) {
        return toAjax(sysWebsiteService.websiteSyncBatch(sysWebsiteDTOList));
    }


    @GetMapping(value = "server")
    public AjaxResult<Server> server() throws Exception {
        Server server = new Server();
        server.copyTo();
        return AjaxResult.success(server);
    }


    @GetMapping(value = "getRsaPublicKey")
    public AjaxResult<String> getRsaPublicKey() throws Exception {
        return AjaxResult.success(SysRsaUtils.getPublicKey());
    }
}
